﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.Kho.UTI;
using ThaiHoa.Win.QLSX.DAL;

namespace ThaiHoa.Win.QLSX.Kho.UI
{
    public partial class frmDoiTacDetail : Form
    {
        #region Fields
        private KhoDBContext db;
        private BindingSource DoiTacBS;
        public Guid Id;
        Access acs;
        public event EventHandler DBChanged;
        #endregion
        #region Constructor
        public frmDoiTacDetail()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void KhoiTao()
        {
            acs = new Access();
            db = new KhoDBContext();
            DoiTacBS = new BindingSource();
            db.DoiTac.Include("NguoiDaiDien").Where(m => m.TrangThai).Load();
            DoiTacBS.DataSource = db.DoiTac.Local.ToBindingList();
            //Binding cho binding navigator
            //Binding cho gridview
            dgvNguoiDaiDien.DataSource = DoiTacBS;
            dgvNguoiDaiDien.DataMember = "NguoiDaiDien";
            //Binding cho textbox
            txtTen.DataBindings.Clear();
            txtTen.DataBindings.Add("Text", DoiTacBS, "TenDonVi");
            txtDiaChi.DataBindings.Clear();
            txtDiaChi.DataBindings.Add("Text", DoiTacBS, "DiaChi");
            txtDienThoai.DataBindings.Clear();
            txtDienThoai.DataBindings.Add("Text", DoiTacBS, "SoDienThoai");
            txtEmail.DataBindings.Clear();
            txtEmail.DataBindings.Add("Text", DoiTacBS, "Email");
            txtFax.DataBindings.Clear();
            txtFax.DataBindings.Add("Text", DoiTacBS, "Fax");
            txtSoTaiKhoan.DataBindings.Clear();
            txtSoTaiKhoan.DataBindings.Add("Text", DoiTacBS, "SoTaiKhoan");
            txtMoTa.DataBindings.Clear();
            txtMoTa.DataBindings.Add("Text", DoiTacBS, "MoTa");
            //Xử lý 2 trường hợp cụ thế :
            //Thêm mới và xem chi tiết
            if (Id != Guid.Empty)// Truong hop xem chi tiet
            {
                //Tìm vị trí của object có Id tương ứng
                int pos = -1;
                //pos = DoiTacBS.Find("MaMatHang","dfi");
                DoiTac item = db.DoiTac.FirstOrDefault(m => m.Id.Equals(Id));
                if (item == null) return;
                pos = DoiTacBS.List.IndexOf(item);
                if (pos < 0)
                    return;
                DoiTacBS.Position = pos;
                this.Text = txtTen.Text;
            }
            else // Truong hop them moi
            {
                DoiTacBS.AddNew();
                this.Text = "New Item";
            }
        }
        private void ReloadData()
        {
            if (db != null) db.Dispose();
            KhoiTao();
            CustomerGridView();
        }
        private void CustomerGridView()
        {
            //ẩn row header
            dgvNguoiDaiDien.RowHeadersVisible = false;
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvNguoiDaiDien.Columns)
            {
                item.Visible = false;
            }
            ////Khóa tính năng thêm mới
            //dgvNguoiDaiDien.AllowUserToAddRows = false;
            //Tùy chỉnh lại
            //Tên
            var c = dgvNguoiDaiDien.Columns["HoVaTen"];
            c.Visible = true;
            c.Width = 150;
            c.DisplayIndex = 1;

            //Địa chỉ
            c = dgvNguoiDaiDien.Columns["DiaChi"];
            c.Visible = true;
            c.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            c.DisplayIndex = 3;

            //Điện thoại
            c = dgvNguoiDaiDien.Columns["DienThoai"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 2;

            //Ẩn đi những row có TrangThai = False
            foreach (DataGridViewRow item in dgvNguoiDaiDien.Rows)
            {
                if (item.Cells["TrangThai"].Value != null)
                {
                    if (!(bool)item.Cells["TrangThai"].Value)
                    {
                        item.Visible = false;
                    }
                }
            }

        }
        /// <summary>
        /// Kiểm tra hợp lệ dữ liệu
        /// True: hợp lệ
        /// False :chưa hợp lệ
        /// </summary>
        /// <returns></returns>
        private bool KiemTraHopLeDuLieu()
        {
            bool result = true;
            errP.Clear();
            if (txtTen.Text == "")
            {
                errP.SetError(txtTen, "Tên không được rỗng");
                result = false;
            }
            return result;
        }
        private int LuuLai()
        {
            DoiTacBS.EndEdit();
            if (!KiemTraHopLeDuLieu()) return -1;
            if (MessageBox.Show("Lưu thay đổi ?", "Lưu Lại", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                int result = db.SaveChanges();
                if (DBChanged != null)
                {
                    DBChanged(this, EventArgs.Empty);
                }
                return result;
            }
            else
                return 0;
        }
        private void Cancel()
        {
            if (MessageBox.Show("Hủy thay đổi ?", "Lưu Lại", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                DoiTacBS.CancelEdit();
                DoiTacBS.ResetCurrentItem();
            }
        }
        private void Xoa()
        {
            if (Id == Guid.Empty)
            {
                this.Close();
                return;
            }
            if (Common.ShowMessengerConfirmDelete() == DialogResult.Yes)
            {
                DoiTacBS.RemoveCurrent();
                db.SaveChanges();
                {
                    DBChanged(this, EventArgs.Empty);
                }
                this.Close();
            }
        }
        private void XoaNguoiDaiDien()
        {
            if ((Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value;
            NguoiDaiDien item = db.NguoiDaiDien.FirstOrDefault(n => n.TrangThai && n.Id.Equals(Id));
            if (item == null) return;
            db.NguoiDaiDien.Remove(item);
            db.SaveChanges();
            ReloadData();
        }
        #endregion


        #region Events
        private void frmDoiTacDetail_Load(object sender, EventArgs e)
        {
            KhoiTao();
            CustomerGridView();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            int result = LuuLai();
            if (result >= 0) this.Close();
        }
        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }
        private void txtTen_TextChanged(object sender, EventArgs e)
        {
            this.Text = txtTen.Text;
        }
        private void btnAddNew_Click(object sender, EventArgs e)
        {
            acs.ShowFormDoiTacDetail(Guid.Empty);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Xoa();
        }
        private void btn_NguoiDaiDien_Edit_Click(object sender, EventArgs e)
        {
            XoaNguoiDaiDien();
        }
        private void btn_NguoiDaiDien_AddNew_Click(object sender, EventArgs e)
        {
            frmNguoiDaiDienDetail _frmNguoiDaiDienDetail = new frmNguoiDaiDienDetail();
            _frmNguoiDaiDienDetail.DBChanged += new EventHandler<NguoiDaiDienEventArgs>(_frmNguoiDaiDienDetail_DBChanged);
            acs.ShowFormNguoiDaiDienDetail(_frmNguoiDaiDienDetail, Guid.Empty);
        }
        private void btn_NguoiDaiDien_Infomation_Click(object sender, EventArgs e)
        {
            if ((Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty) return;
            frmNguoiDaiDienDetail _frmNguoiDaiDienDetail = new frmNguoiDaiDienDetail();
            _frmNguoiDaiDienDetail.DBChanged += new EventHandler<NguoiDaiDienEventArgs>(_frmNguoiDaiDienDetail_DBChanged);
            acs.ShowFormNguoiDaiDienDetail(_frmNguoiDaiDienDetail, Id);
        }
        void _frmNguoiDaiDienDetail_DBChanged(object sender, NguoiDaiDienEventArgs e)
        {
            switch (e.Type)
            { 
                case 1://Thêm mới
                    ((DoiTac)DoiTacBS.Current).NguoiDaiDien.Add(e.NguoiDaiDien);
                    dgvNguoiDaiDien.DataSource = null;
                    dgvNguoiDaiDien.DataSource = DoiTacBS;
                    dgvNguoiDaiDien.DataMember = "NguoiDaiDien";
                    CustomerGridView();
                    break;
                case 2://Edit
                    NguoiDaiDien item=((DoiTac)DoiTacBS.Current).NguoiDaiDien.FirstOrDefault(n=>n.TrangThai && n.Id.Equals(e.NguoiDaiDien.Id));
                    if(item ==null) return;;
                    ((DoiTac)DoiTacBS.Current).NguoiDaiDien.Remove(item);
                    ((DoiTac)DoiTacBS.Current).NguoiDaiDien.Add(e.NguoiDaiDien);
                    dgvNguoiDaiDien.DataSource = null;
                    dgvNguoiDaiDien.DataSource = DoiTacBS;
                    dgvNguoiDaiDien.DataMember = "NguoiDaiDien";
                    CustomerGridView();
                    break;

            }
        }
        private void dgvNguoiDaiDien_DoubleClick(object sender, EventArgs e)
        {
            if ((Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value == null) return;
            Guid Id = (Guid)dgvNguoiDaiDien.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty) return;
            frmNguoiDaiDienDetail _frmNguoiDaiDienDetail = new frmNguoiDaiDienDetail();
            _frmNguoiDaiDienDetail.DBChanged += new EventHandler<NguoiDaiDienEventArgs>(_frmNguoiDaiDienDetail_DBChanged);
            acs.ShowFormNguoiDaiDienDetail(_frmNguoiDaiDienDetail, Id);

        }
        #endregion

        

        

        

        
    }
}
